//app.js
const util = require("./utils/util.js");
const Promise = require("./plugins/es6-promise.js"); 
require("utils/sdk/libs/strophe");
let WebIM = require("./utils/WebIM")["default"];
let msgStorage = require("comps/chat/msgstorage");
let msgType = require("comps/chat/msgtype");
let disp = require("utils/broadcast");

function ack(receiveMsg) {
  // 处理未读消息回执
  var bodyId = receiveMsg.id;         // 需要发送已读回执的消息id
  var ackMsg = new WebIM.message("read", WebIM.conn.getUniqueId());
  ackMsg.set({
    id: bodyId,
    to: receiveMsg.from
  });
  WebIM.conn.send(ackMsg.body);
}

function onMessageError(err) {
  if (err.type === "error") {
    wx.showToast({
      title: err.errorText
    });
    return false;
  }
  return true;
}

function getCurrentRoute() {
  let pages = getCurrentPages();
  let currentPage = pages[pages.length - 1];
  return currentPage.route;
}

function calcUnReadSpot() {
  let myName = wx.getStorageSync("myUsername");
  let members = wx.getStorageSync("member") || []; 
  let count = members.reduce(function (result, curMember, idx) {
    let chatMsgs = wx.getStorageSync(curMember.name + myName) || [];
    return result + chatMsgs.length;
  }, 0);
  getApp().globalData.unReadSpot = count > 0;
  disp.fire("em.xmpp.unreadspot", count);
}
App({
  onLaunch: function() {
    
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || [];
    logs.unshift(Date.now());
    wx.setStorageSync('logs', logs);
    // wx.showLoading({
    //     title: '加载中',
    //     mask:true
    // })

    //初始化工具类，全局使用
    this.util = util;

    //全局添加图片域名前缀
    this.image_prefix_host = util.getImagePrefixHost();

    //全局添加域名前缀
    this.globalData.addr = util.getImagePrefixHost('addr');

    //全局添加文件服务器前缀
    this.globalData.cdnaddr = util.getImagePrefixHost('cdnaddr');

    //全局添加app服务器前缀
    this.globalData.appaddr = util.getImagePrefixHost('appaddr');

    //全局添加app服务器前缀
    this.globalData.imAddr = util.getImagePrefixHost('imAddr');
    this.userLogin();
  },
  imloign: function (user, pwd) {
    // var options = {
    //   apiUrl: WebIM.config.apiURL,
    //   user: '109',
    //   pwd: '00f0f2ca-c8c8-4124-bf7a-234de694ac97',
    //   grant_type: 'password',
    //   appKey: WebIM.config.appkey //应用key
    // }
    var options = {
      apiUrl: WebIM.config.apiURL,
      user: user,
      pwd: pwd,
      grant_type: 'password',
      appKey: WebIM.config.appkey //应用key
    }
    
    WebIM.conn.open(options)
  },
  
  userLogin:function(){
    var that = this
    wx.login({
      success: function (res) {
        //获取openId
        wx.request({
          url: getApp().globalData.testAddr + "wxlogin/getOpenId?code=" + res.code,
          data: {
          },
          method: 'POST',
          header: { 'content-type': 'application/json' },
          success: function (openIdRes) {
            let openid = openIdRes.data.openid;
            wx.setStorageSync('openId', openid)
            // 判断openId是否获取成功
            if (openid != null && openid != undefined) {
              that.util.request({
                url: getApp().globalData.testAddr + "Guest/login?wechat=" + openid,
                method: "POST",
                data: {},
                success: function (res) {
                  var jsonStr = res;
                  if (typeof jsonStr != 'object' && jsonStr != '') {
                    jsonStr = jsonStr.replace(/\ufeff/g, "");//重点
                    var jsonStr = JSON.parse(jsonStr);
                  }
                  var list = JSON.parse(jsonStr.data);
                  console.log(jsonStr.data);
                  wx.setStorageSync('list', list)
                  wx.setStorage({
                    key: "myUsername",
                    data: list.guestid
                  });
                  var user = list.guestid;
                  var pwd = list.chatPwd;
                  that.detail(user.toString());
                  that.imloign(user.toString(), pwd.toString())
                },
                fail: function (res) {

                },
                complete: function (res) {

                },
              });
            } else {
              console.info("获取用户openId失败");
            }
          },
          fail: function (error) {
            console.info("获取用户openId失败");
            console.info(error);
          }
        })

      }
    })
  },
  //  根据guestid查询详细信息
  detail: function (id) {
    var that = this
    var arr;
    getApp().util.request({
      url: getApp().globalData.testAddr + "/Guest/GetInfoByID?guestID=" + id,
      method: "POST",
      data: {},
      success: function (res) {
        arr = res.data
        wx.setStorage({
          key: "headUrl",
          data: 'https://www.goods-asked.cn:6061/img/guest/'+arr.imgUrl
        });
      },
      fail: function (res) {

      },
      complete: function (res) {
        wx.hideLoading()
      },
    });
  },
  globalData: {
    testAddr: "https://www.goods-asked.cn/hwsjEmp/",
    appaddr: "",
    cdnaddr: "",
    imAddr: "",
    role: null,
    version: '1.0.7',
    openid: "",
    user: {},
    imgurl: "https://www.goods-asked.cn:6061/img/",


    unReadSpot: false,
    userInfo: null,
    saveFriendList: []
  },
})